package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import utils.SqlSessionFactoryUtils;

public class UserService {
    //使用工具类获取SqlSessionFactory
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    /*** 登录方法 */
    public User login(String username, String password){
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //3. 调用方法
        User user = userMapper.selectByUsername(username);
        //4. 释放资源
//        sqlSession.close();
        //5. 验证密码
        if(user != null){
            //继续对比密码
            if(password.equals(user.getPassword())){
                //验证通过
                return user;
            }else{
                //密码不符
                return null;
            }
        }
        //因为用户不存在导致登录失败
        return null;
    }
    //添加新用户
    public boolean register(String username, String password){
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
         //3. 调用方法
        User user= userMapper.selectByUsername(username);
        //4.提交事务
       if (user!=null){
           return  false;
       }
       User newUser = new User(null,username,password);
       int   i= userMapper.add(newUser);
        sqlSession.commit();
        sqlSession.close();
       return  i>0;
    }
    //检查用户名是否存在
    public boolean checkUsername(String username){
        //1. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //2. 获取UserMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //3. 调用方法
        User user= userMapper.selectByUsername(username);
        //4.提交事务
        if (user!=null){
            return  true;
        }
        sqlSession.close();
        return  false;
    }

}